package com.party.admin.web.controller.circle;

import com.party.admin.biz.circle.CircleBizNewService;
import com.party.admin.biz.file.FileBizService;
import com.party.admin.biz.photo.AlbumBizService;
import com.party.core.utils.MyBeanUtils;
import com.party.admin.utils.RealmUtils;
import com.party.admin.web.dto.AjaxResult;
import com.party.admin.web.dto.input.circle.CircleInput;
import com.party.admin.web.dto.input.common.CommonInput;
import com.party.api.dto.wechat.requst.XcxQrCodeRequest;
import com.party.common.constant.Constant;
import com.party.common.paging.Page;
import com.party.core.model.circle.Circle;
import com.party.core.model.circle.CircleCode;
import com.party.core.model.circle.CircleTag;
import com.party.core.model.circle.WithTage;
import com.party.core.model.city.Area;
import com.party.core.model.photo.PhotoProject;
import com.party.core.model.system.Dict;
import com.party.core.model.system.DictEnum;
import com.party.core.model.wechatPlatform.WechatOpenMember;
import com.party.core.service.circle.ICircleService;
import com.party.core.service.circle.ICircleTagService;
import com.party.core.service.circle.biz.CircleBizService;
import com.party.core.service.circle.biz.CircleMemberBizService;
import com.party.core.service.city.IAreaService;
import com.party.core.service.cos.CosBizService;
import com.party.core.service.member.IMemberAdministratorService;
import com.party.core.service.photo.IPhotoProjectService;
import com.party.core.service.system.IDictService;
import com.party.core.service.wechatPlatform.IWechatOpenMemberService;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.weaver.loadtime.Aj;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 圈子
 */
@Controller
@RequestMapping(value = "/circle")
public class CircleController {

	@Autowired
	private ICircleService circleService;
	@Autowired
	private IAreaService areaService;
	@Autowired
	private IDictService dictService;
	@Autowired
	private CircleBizService circleBizService;
	@Autowired
	private FileBizService fileBizService;
	@Autowired
	private ICircleTagService circleTagService;
	@Autowired
	private CosBizService cosBizService;
	@Autowired
	private CircleMemberBizService circleMemberBizService;
	@Autowired
	private IWechatOpenMemberService wechatOpenMemberService;
	@Autowired
	private IPhotoProjectService photoProjectService;
	@Autowired
	private AlbumBizService albumBizService;
	@Autowired
	private CircleBizNewService circleBizNewService;
	@Autowired
	private IMemberAdministratorService memberAdministratorService;

	Logger logger = LoggerFactory.getLogger(getClass());


	/**
	 * 圈子列表页面
	 */
	@RequestMapping(value = { "list", "" })
	public ModelAndView list(Page page, Circle circle, CommonInput commonInput) {
		page.setLimit(20);
		ModelAndView mv = new ModelAndView("circle/circleList");
		Map<String, Object> param = CommonInput.appendParams(commonInput);

		if (null != param.get("startDate")) {
			commonInput.setCreateStart(param.get("startDate").toString().substring(0, "2018-05-04".length()));
		}
		if (null != param.get("endDate")) {
			commonInput.setCreateEnd(param.get("endDate").toString().substring(0, "2018-05-04".length()));
		}

		mv.addObject("input", commonInput);

		Map<String, Object> params = RealmUtils.getMemberAdministrator(param,memberAdministratorService);

			List<Map<String, Object>> list = circleService.webListPage(circle, params, page);
		for (Map<String, Object> item : list) {
			String filePath = fileBizService.getUploadCIPath(item.get("create_by").toString(), "circle");
			String qrCodeUrl = cosBizService.getPreviewPictureUrl(filePath + item.get("id"));
			item.put("qrCodeUrl", qrCodeUrl);

			String fileContactPath = fileBizService.getUploadCIPath(item.get("create_by").toString(), "circle/contact");
			String qrABCodeUrl = cosBizService.getPreviewPictureUrl(fileContactPath + item.get("id"));
			item.put("qrABCodeUrl",qrABCodeUrl);
		}
		mv.addObject("list", list);
		mv.addObject("page", page);
		mv.addObject("circle", circle);
		return mv;
	}

	/**
	 * 查看，增加，编辑圈子表单页面
	 */
	@RequestMapping(value = "form")
	public ModelAndView form(Circle circle) {
		ModelAndView mv = new ModelAndView("circle/circleForm");
		if (StringUtils.isNotBlank(circle.getId())) {
			circle = circleService.get(circle.getId());

			CircleTag t = new CircleTag();
			t.setCircle(circle.getId());
			List<CircleTag> circleTags = circleTagService.list(t);
			mv.addObject("circleTags", circleTags);
		}
		if (StringUtils.isNotEmpty(circle.getArea())) {
			Area area = areaService.get(circle.getArea());
			mv.addObject("city", area.getId());
			mv.addObject("arParent", area.getParentId());
		}

		Dict dict = new Dict();
        dict.setType(DictEnum.CIRCLE_TYPE.getCode());
        mv.addObject("types", dictService.list(dict));
		mv.addObject("circle", circle);
		Area area = new Area();
		area.setParentId("1");
		List<Area> areas = areaService.list(area);
		mv.addObject("areas", areas);
		return mv;
	}

	/**
	 * 保存圈子
	 */
	@ResponseBody
	@RequestMapping(value = "save")
	public AjaxResult save(CircleInput circleInput, BindingResult result) throws Exception {
		try {
			// 数据验证
			if (result.hasErrors()) {
				List<ObjectError> allErros = result.getAllErrors();
				return AjaxResult.error(allErros.get(0).getDefaultMessage());
			}
			circleInput.setMemo(circleInput.getMemo().trim());
			// 以下内容暂时写在controller 因为core里没有myBeanUtils类
			Circle qrCircle = null;
			if (StringUtils.isNotEmpty(circleInput.getId())) {// 编辑表单保存
				Circle circleDb = circleService.get(circleInput.getId());
				MyBeanUtils.copyBeanNotNull2Bean(circleInput, circleDb);// 将编辑表单中的非\NULL值覆盖数据库记录中的值
				circleInput.setUpdateBy(RealmUtils.getCurrentUser().getId());

				if (circleInput.getCircleTags() != null) {
					if (circleInput.getIsOpen().equals(CircleCode.CIRCLE_AUTH_TYPE_AUTH.getCode())) {
						for (CircleTag circleTag : circleInput.getCircleTags()) {
							if (circleTag.getTagName().equals("其他")) {
								circleDb.setNoTypeIsOpen(circleTag.getIsOpen());
							} else {
								CircleTag t = circleTagService.get(circleTag.getId());
								t.setIsOpen(circleTag.getIsOpen());
								circleTagService.update(t);
							}
						}
					} else {
						for (CircleTag circleTag : circleInput.getCircleTags()) {
							if (circleTag.getTagName().equals("其他")) {
								circleDb.setNoTypeIsOpen(null);
							} else {
								CircleTag t = circleTagService.get(circleTag.getId());
								t.setIsOpen(null);
								circleTagService.update(t);
							}
						}
					}
				}
				circleService.update(circleDb);
				qrCircle = circleDb;
			} else {
				circleInput.setCreateBy(RealmUtils.getCurrentUser().getId());
				Circle circle = new Circle();
				MyBeanUtils.copyBeanNotNull2Bean(circleInput, circle);// 将编辑表单中的非\NULL值覆盖数据库记录中的值
				circleService.insert(circle);
				qrCircle = circle;
			}

			circleBizNewService.uploadQrCode(qrCircle.getCreateBy(), qrCircle.getId());
			return AjaxResult.success();
		} catch (Exception e) {
			logger.error("圈子保存异常", e);
			return AjaxResult.error("圈子保存异常");
		}
	}

	/**
	 * 解散圈子
	 */
	@ResponseBody
	@RequestMapping(value = "dissolveCircle")
	public AjaxResult dissolveCircle(String id) {
		AjaxResult ajaxResult = new AjaxResult();
		try {
			Map<String, Object> searchMap = new HashMap<String, Object>();
			searchMap.put("circleId", id);
			List<WithTage> list = circleMemberBizService.withTageList(searchMap, null);
			if(list.size() == 0 ){
				circleBizService.dissolveCircle(id);
				return new AjaxResult(true);
			}else {
				return new AjaxResult(false, "项目下已有会员，不能删除");
			}
		} catch (Exception e) {
			ajaxResult.setSuccess(false);
		}
		return new AjaxResult(false);
	}

	/**
	 * 删除圈子
	 */
	@ResponseBody
	@RequestMapping(value = "delete")
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public AjaxResult delete(String id) {
		Circle circle = circleService.get(id);
		if (circle == null) {
			return AjaxResult.error("圈子不存在");
		}
		String filePath = fileBizService.getUploadCIPath(circle.getCreateBy(), "circle");
		boolean result = circleBizService.deleteCircleBiz(id, filePath);
		if (result) {
			return AjaxResult.success();
		} else {
			return AjaxResult.error("删除圈子异常");
		}
	}

	@ResponseBody
	@RequestMapping("initQrCode")
	public AjaxResult initQrCode(){
		List<Circle> list = circleService.list(new Circle());
		for (Circle circle : list) {
			String filePath = fileBizService.getUploadCIPath(circle.getCreateBy(), "circle");
			String qrContent = "circle/circle_detail.html?id=" + circle.getId();
			String localPath = circle.getCreateBy() + "/circle/";
			fileBizService.uploadCloudOut(circle.getId(), filePath, localPath, circle.getId(), qrContent, circle.getCreateBy());
		}
		return AjaxResult.success();
	}

	/**
	 * 生成相册
	 */
	@ResponseBody
	@RequestMapping(value = "createPhotos")
	public AjaxResult createPhotosProject( String id) {
		AjaxResult ajaxResult = new AjaxResult();
		try {
			Circle circle = circleService.get(id);
			PhotoProject photoProject = new PhotoProject();
			photoProject.setMemberId(circle.getCreateBy());
			photoProject.setCircleId(circle.getId());
			photoProject.setName(circle.getName());
			photoProject.setOperatePermission(1);
			if(circle.getMemo() != null ) {
				photoProject.setIntroduction(circle.getMemo());
			}
			if(circle.getLogo() != null ) {
				photoProject.setPic(circle.getLogo());
			}
			List<PhotoProject> photosList =  photoProjectService.list(photoProject);
			if (photosList.size() == 0) {
				photoProjectService.insert(photoProject);
				// 初始化系统标签
				albumBizService.initTags(photoProject.getId());
			} else {
				PhotoProject oldPhotoProject = photosList.get(0);
				oldPhotoProject.setName(circle.getName());
				oldPhotoProject.setPic(circle.getLogo());
				if(circle.getMemo() != null ) {
					oldPhotoProject.setIntroduction(circle.getMemo());
				}
				photoProjectService.update(oldPhotoProject);
			}
			try {
				WechatOpenMember openMember = wechatOpenMemberService.findByType(Constant.WECHAT_ACCOUNT_TYPE_SYSTEM_XCX_PHOTO);
				XcxQrCodeRequest qrCodeRequest = new XcxQrCodeRequest();
				qrCodeRequest.setPage("pages/photo/index");
				qrCodeRequest.setScene(photoProject.getId());
				String filePath = fileBizService.getUploadCIPath(circle.getCreateBy(), "photo");
				fileBizService.uploadCloudOut(photoProject.getId(), filePath, qrCodeRequest, openMember.getAuthorizerAccessToken(), 1);
			} catch (Exception e) {
				logger.error("生成小程序码异常", e);
			}
		} catch (Exception e) {
			ajaxResult.setSuccess(false);
		}
		return AjaxResult.success();
	}


	@ResponseBody
	@RequestMapping("init/cricle/qrCodeUrl")
	public AjaxResult intiCricleQrCodeUrl() {
		try {

			List<Circle> circleList = circleService.listAll();

			for (Circle circle : circleList) {
				String memberId = circle.getCreateBy();
				String circleId = circle.getId();
				//上传通讯录二维码
				String fileContactPath = fileBizService.getUploadCIPath(memberId, "circle/contact");
				String contactQrContent = "circle/circle_contact.html?id="+circleId;
				fileBizService.uploadCloudOut(circleId, fileContactPath, contactQrContent, memberId);
			}
			return AjaxResult.success();
		} catch (Exception e) {
			logger.error("初始化通讯录二位码异常",e);
			return AjaxResult.error("初始化通讯录二位码异常");
		}

	}
}
